package com.jzo2o.foundations.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.RegionResDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeItemService;
import com.jzo2o.foundations.service.IServeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private IServeItemService itemService;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private ServeItemMapper serveItemMapper;

    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO dto) {
        Page page = new Page(dto.getPageNo(),dto.getPageSize());
        IPage<ServeResDTO> iPage = baseMapper.selectServeRangePage(page,dto.getRegionId());
        return new PageResult<>(iPage.getPages(),iPage.getTotal(),iPage.getRecords());
    }

    @Override
    public void saveBatch(List<ServeUpsertReqDTO> dtoList) {
        if (CollectionUtil.isEmpty(dtoList)){
            log.error("参数为空");
            throw new ForbiddenOperationException("参数为空");
        }
        Long regionId = dtoList.get(0).getRegionId();

        List<Long> itemIds = dtoList.stream()
                .map(ServeUpsertReqDTO::getServeItemId)
                .collect(Collectors.toList());

        List<ServeItem> itemList = itemService.listByIds(itemIds);
        if (CollectionUtil.isEmpty(itemList)){
            log.error("服务不存在");
            throw new ForbiddenOperationException("服务不存在");
        }

        if (dtoList.size() != itemList.size()){
            log.error("有服务不存在");
            throw new ForbiddenOperationException("有服务不存在");
        }

        for (ServeItem serveItem : itemList) {
            if (serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()){
                log.error("服务状态不可用");
                throw new ForbiddenOperationException("服务状态不可用");
            }
        }

        List<Serve> serveItemIdList = lambdaQuery()
                .select(Serve::getServeItemId)
                .eq(Serve::getRegionId, regionId)
                .list();

        if (!CollectionUtil.isEmpty(serveItemIdList)) {
            for (Serve serve : serveItemIdList) {
                Long serveItemId = serve.getServeItemId();
                for (ServeUpsertReqDTO serveDto : dtoList) {
                    if (serveDto.getServeItemId().equals(serveItemId)){
                        log.error("服务已存在");
                        throw new ForbiddenOperationException("服务已存在");
                    }
                }
            }
        }

        Region region = regionMapper.selectById(regionId);
        if (region == null){
            log.error("区域不存在");
            throw new ForbiddenOperationException("区域不存在");
        }

        String cityCode = region.getCityCode();
        List<Serve> serveList = new ArrayList<>();
        for (ServeUpsertReqDTO dto : dtoList) {
            Serve serve = new Serve();
            serve.setServeItemId(dto.getServeItemId());
            serve.setRegionId(dto.getRegionId());
            serve.setCityCode(cityCode);
            serve.setPrice(dto.getPrice());
            serveList.add(serve);
        }
        baseMapper.insertBatch(serveList);
    }

    @Override
    public void updatePriceById(Long id, BigDecimal price) {
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if (!update){
            log.error("修改服务价格失败");
            throw new CommonException("修改服务价格失败");
        }
    }

    @Override
    public void updateOnSaleStatusById(Long id) {

        Serve serve = baseMapper.selectById(id);
        if (serve == null){
            log.error("区域服务不存在");
            throw new ForbiddenOperationException("区域服务不存在");
        }

        Integer saleStatus = serve.getSaleStatus();
        if (!(saleStatus == FoundationStatusEnum.INIT.getStatus() || saleStatus == FoundationStatusEnum.DISABLE.getStatus())){
            log.error("草稿或下架状态方可上架");
            throw new ForbiddenOperationException("草稿或下架状态方可上架");
        }

        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if (serveItem == null){
            log.error("服务项不存在");
            throw new ForbiddenOperationException("服务项不存在");
        }

        Integer activeStatus = serveItem.getActiveStatus();
        if (!(activeStatus == FoundationStatusEnum.ENABLE.getStatus())){
            log.error("服务项为启用状态方可上架");
            throw new ForbiddenOperationException("服务项为启用状态方可上架");
        }

        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if (!update){
            log.error("修改服务状态失败");
            throw new CommonException("修改服务状态失败");
        }
    }

    @Override
    public void deleteById(Long id) {

        Serve serve = baseMapper.selectById(id);
        if (serve == null){
            log.error("区域服务不存在");
            throw new ForbiddenOperationException("区域服务不存在");
        }

        Integer saleStatus = serve.getSaleStatus();
        if (saleStatus != FoundationStatusEnum.INIT.getStatus()){
            log.error("草稿状态方可删除");
            throw new ForbiddenOperationException("草稿状态方可删除");
        }

        baseMapper.deleteById(id);
    }

    @Override
    public void updateOffSaleStatusById(Long id) {

        Serve serve = baseMapper.selectById(id);
        if (serve == null){
            log.error("区域服务不存在");
            throw new ForbiddenOperationException("区域服务不存在");
        }

        Integer saleStatus = serve.getSaleStatus();
        if (saleStatus != FoundationStatusEnum.ENABLE.getStatus()){
            log.error("上架状态方可下架");
            throw new ForbiddenOperationException("上架状态方可下架");
        }

        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .set(Serve::getIsHot,0)
                .update();
        if (!update){
            log.error("区域服务下架失败");
            throw new CommonException("区域服务下架失败");
        }
    }

    @Override
    public void updateOnHotById(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (serve == null){
            log.error("区域服务不存在");
            throw new ForbiddenOperationException("区域服务不存在");
        }

        Integer saleStatus = serve.getSaleStatus();
        if (saleStatus != FoundationStatusEnum.ENABLE.getStatus()){
            log.error("上架状态方可设置热门");
            throw new ForbiddenOperationException("上架状态方可设置热门");
        }

        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot,1)
                .update();
        if (!update){
            log.error("设置热门服务失败");
            throw new CommonException("设置热门服务失败");
        }
    }

    @Override
    public void updateOffHotById(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (serve == null){
            log.error("区域服务不存在");
            throw new ForbiddenOperationException("区域服务不存在");
        }

        Integer saleStatus = serve.getSaleStatus();
        if (saleStatus != FoundationStatusEnum.ENABLE.getStatus()){
            log.error("上架状态方可取消设置热门");
            throw new ForbiddenOperationException("上架状态方可取消设置热门");
        }

        Integer isHot = serve.getIsHot();
        if (isHot != 1){
            log.error("热门服务方可取消热门设置");
            throw new ForbiddenOperationException("热门服务方可取消热门设置");
        }

        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot,2)
                .update();
        if (!update){
            log.error("取消设置热门服务失败");
            throw new CommonException("取消设置热门服务失败");
        }
    }

}
